package com.fudan.framework.base;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * controller的基类，封装log以及一些页面使用的参数
 * @author Xuxinxing
 *
 */
public abstract class BaseController {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	protected final String SUCCESS = "操作成功";
	protected final String ERROR = "error";

	protected final Integer SUCCESS_CODE = 0;
	protected final Integer SYSTEM_ERROR_CODE = 500;
	protected final Integer ADD_ERROR_CODE = 100;
	protected final Integer DELETE_ERROR_CODE = 103;
	protected final Integer FIND_ERROR_CODE = 101;
	protected final String FIND_ERROR_MSG = "查找失败";
	protected final Integer UPDATE_ERROR_CODE = 102;

	public static class PageBean {
		private Integer page;
		private Integer size;
		private PageBean(int page,int size) {
			this.page = page;
			this.size = size;
		}
		public Integer getPage() {
			return page;
		}
		public void setPage(Integer page) {
			this.page = page;
		}
		public Integer getSize() {
			return size;
		}
		public void setSize(Integer size) {
			this.size = size;
		}

		public Integer getPageIndex() {
			return page-1;
		}

		public static PageBean build(int page,int size) {
			return new PageBean(page, size);
		}
		public static PageBean of(HttpServletRequest request) {
			String pageStr = request.getParameter("page");
			String sizeStr = request.getParameter("limit");
			int page = 1;
			int size = 10;
			if(pageStr!=null && pageStr.matches("[0-9]+")) {
				page = Integer.parseInt(pageStr);
			}
			if(sizeStr!=null && sizeStr.matches("[0-9]+")) {
				size = Integer.parseInt(sizeStr);
			}
			return new PageBean(page, size);
		}
	}

	protected String R(Boolean result) {
		if(result) {
			return SUCCESS;
		}else {
			return ERROR;
		}
	}

	protected String fetchSearchVal(HttpServletRequest request) {
		return request.getParameter("search_value");
	}

	protected PageBean buildPage(HttpServletRequest request) {
		String pageStr = request.getParameter("page");
		String sizeStr = request.getParameter("limit");
		int page = 1;
		int size = 10;
		if(pageStr!=null && pageStr.matches("[0-9]+")) {
			page = Integer.parseInt(pageStr);
		}
		if(sizeStr!=null && sizeStr.matches("[0-9]+")) {
			size = Integer.parseInt(sizeStr);
		}
		return PageBean.build(page, size);
	}

	protected Integer fetchInt(HttpServletRequest request,String fieldName) {
		String parameter = request.getParameter(fieldName);
		if(parameter!=null&&parameter.matches("[0-9]+")) {
			return Integer.parseInt(parameter);
		}
		return null;
	}
}
